package com.yc.d0422;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class URLDemo {

    public static void main(String[] args) throws IOException {
        String address = "http://www.hyycinfo.com/index.html";
        URL url = new URL(address);
        System.out.println("url.getProtocol() = " + url.getProtocol());
        System.out.println("url.getHost() = " + url.getHost());
        System.out.println("url.getPath() = " + url.getPath());
        System.out.println("url.getPort() = " + url.getPort());
        final URLConnection conn = url.openConnection();
        // 字符集
        System.out.println("conn.getContentEncoding() = " + conn.getContentEncoding());
        // 资源类型
        System.out.println("conn.getContentType() = " + conn.getContentType());
        // 大小
        System.out.println("conn.getContentLength() = " + conn.getContentLength());
        String diskpath = "d:/a/" + url.getFile();

        try (final InputStream in = conn.getInputStream();
             // 字节流转字符流
             // InputStreamReader isr = new InputStreamReader(in);
             // FileWriter
             FileOutputStream fos = new FileOutputStream(diskpath);
        ) {
            byte[] bytes = new byte[1024];
            int count;
            while ((count = in.read(bytes)) > -1) {
                String s = new String(bytes, 0 , count);
                System.out.print(s);
                // 输出到文件
                fos.write(bytes, 0, count);
            }
        }
    }


}
